package walkera.cn.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
import walkera.cn.bean.HeartBeatTask;
import walkera.cn.tool.WkHeartBeatTool;


@SuppressLint("AppCompatCustomView")
public class LongPressBtn extends Button {
    private  OnLongTouchResult onLongTouchResult;
    private int viewId = -100 ;
    public LongPressBtn(Context context) {
        super(context);
        initView();
    }

    public LongPressBtn(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public LongPressBtn(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView(){
        viewId = this.getId() ;
    }


    /**
     * @param downPicId  R.drawable.btn_bg2
     * @param upPicID  R.drawable.btn_bg
     */
    public void init(final WkHeartBeatTool wkHeartBeatTool,
                     final OnLongTouchResult onLongTouchResult0,
                     final int downPicId ,
                     final int upPicID
    ){
        this.onLongTouchResult = onLongTouchResult0;


        this.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    wkHeartBeatTool.startTheBeatAction(setPointsPauseResumeStateTask, 200);
                    LongPressBtn.this.setBackgroundResource(downPicId);
                    break;
                case MotionEvent.ACTION_CANCEL:
                    break;
                case MotionEvent.ACTION_UP:
                    LongPressBtn.this.setBackgroundResource(upPicID);
                    wkHeartBeatTool.shutDownTheBeatAction(setPointsPauseResumeStateTask);
                    if(onLongTouchResult!=null){
                            onLongTouchResult.onStopPress(viewId);
                    }
                    performClick();
                    break;
                default:
                    break;
            }
            return true;
        }
        );

    }


    private HeartBeatTask setPointsPauseResumeStateTask = new HeartBeatTask() {
        @Override
        public void run() {
            if (onLongTouchResult != null) {
                onLongTouchResult.getLongAction(viewId);
            }
        }
    };

    @Override
    public boolean performClick() {
        return super.performClick();
    }


    public interface OnLongTouchResult {
        /**持续长按*/
        void getLongAction(int viewId);
        /**停止长按*/
        void onStopPress(int viewId);
    }
}
